package com.humble.vichatbackend.service.impl;

import com.humble.vichatbackend.exception.BusinessException;
import com.humble.vichatbackend.mapper.UserTeamMapper;
import com.humble.vichatbackend.model.enums.ErrorCode;
import com.humble.vichatbackend.service.ChatService;
import com.humble.vichatbackend.service.UserService;
import com.humble.vichatbackend.web_socket.ChatSocket;
import com.humble.vichatbackend.web_socket.ChatSocketManager;
import jakarta.websocket.Session;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;


@Service
@Slf4j
public class ChatServiceImpl implements ChatService {
    UserService userService;
    ChatSocketManager chatSocketManager;
    UserTeamMapper userTeamMapper;

    @Autowired
    ChatServiceImpl(UserService userService, ChatSocketManager chatSocketManager, UserTeamMapper userTeamMapper) {
        this.userService = userService;
        this.chatSocketManager = chatSocketManager;
        this.userTeamMapper = userTeamMapper;
    }

    @Override
    public void connect(Long id, Long teamId, Session session) {
        // 先加入统一的连接管理中
        ChatSocketManager.USER_SESSION_MAP.put(id, session);
        // 具体聊天室
        if (teamId != -1) {
            ChatSocket chatSocket = ChatSocketManager.CHAT_SOCKET_MAP.get(teamId);
            chatSocket.ONLINE_USER_MAP.put(id, session);
            chatSocket.sendLeaveMessage(id);
        }
        // 用户重新上线
        else {
            List<Long> teamIds = userTeamMapper.selectTeamIdsByUserId(id);
            for (Long tId : teamIds) {
                ChatSocket chatSocket = ChatSocketManager.CHAT_SOCKET_MAP.get(teamId);
                if (chatSocket != null) {
                    chatSocket.ONLINE_USER_MAP.put(id, session);
                    chatSocket.sendLeaveMessage(id);
                } else {
                    log.error("聊天室出现异常，异常聊天室teamId:{}", tId);
                }
            }
        }
    }

    @Override
    public void sendMessage(Long id, Long teamId, String message) {
        ChatSocket chatSocket = ChatSocketManager.CHAT_SOCKET_MAP.get(teamId);
        if(!chatSocket.getONLINE_USER_MAP().containsKey(id)){
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        chatSocket.sendToAll(id, message);
    }

    @Override
    public void closeConnection(Long id, Long teamId) {

        ChatSocket chatSocket = ChatSocketManager.CHAT_SOCKET_MAP.get(teamId);
        if (chatSocket != null) {
            Session remove = chatSocket.ONLINE_USER_MAP.remove(id);
            try {
                remove.close();
            } catch (IOException e) {
                log.error("会话关闭失败，具体错误：{}", e.getMessage());
            }
        }
        else{
            Session session = ChatSocketManager.USER_SESSION_MAP.get(id);
            try {
                session.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

    }
}
